package cn.com.bo.util.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.bo.util.PropUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SSHUtils {
	
	private static Logger log = LoggerFactory.getLogger(SSHUtils.class);

	public static boolean exe(SSHModel param) {
		// 指明连接主机的IP地址
		Connection conn = param.getConn();
		Session ssh = null;
		try {
			// 连接到主机
			conn.connect();
			// 使用用户名和密码校验
			boolean isconn = conn.authenticateWithPassword(param.getUsername(),
					param.getPassword());
			if (!isconn) {
				log.error("用户名称或者是密码不正确");
				return false;
			} else {
				log.info("ssh link success!");
				ssh = conn.openSession();
				log.info("Execute command line: "+param.getCommand());
				// 使用多个命令用分号隔开
				// ssh.execCommand("pwd;cd /tmp;mkdir hb;ls;ps -ef|grep weblogic");
				ssh.execCommand(param.getCommand());
//				System.out.println(param.getCommand());
				// 只允许使用一行命令，即ssh对象只能使用一次execCommand这个方法，多次使用则会出现异常
				// ssh.execCommand("mkdir hb");
				// 将屏幕上的文字全部打印出来
				InputStream is = new StreamGobbler(ssh.getStdout());
				BufferedReader brs = new BufferedReader(new InputStreamReader(
						is));
				String s;
				while ((s = brs.readLine()) != null) {
					log.info(s);
				}
				brs.close();
				is.close();
			}
			// 连接的Session和Connection对象都需要关闭
			ssh.close();
			conn.close();

		} catch (IOException e) {
			log.error("ERROR:Command line error!{}",e.getMessage());
		}
		return true;
	}


}
